package com.zhb.cms.oauth.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

import com.zhb.cms.oauth.custom.CustomPasswordEncoderUtil;

/**
 * user login cofig
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{

	@Autowired
	private DataSource dataSource;

	@Override
	protected void configure(HttpSecurity http) throws Exception
	{
		//配置请求拦截设置
		// @formatter:off
		http.formLogin().loginPage("/login").permitAll().and().requestMatchers()
				.antMatchers("/**", "/oauth/authorize", "/oauth/confirm_access").and().authorizeRequests().anyRequest()
				.authenticated().and().logout().deleteCookies("remove").invalidateHttpSession(true)
				.logoutSuccessUrl("/").permitAll().and().csrf()
				.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
		// @formatter:on
	}

	/**
	 * user cofig
	 */
	@Autowired
	public void globalUserDetails(final AuthenticationManagerBuilder auth) throws Exception
	{
		//配置用户查询和用户角色查询以及密码加密模式
		auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery(getUserQuery())
				.authoritiesByUsernameQuery(getAuthoritiesQuery());
		
	}

	/**
	 * 密码加密模式
	 * md5 encoder cofig
	 */
	public Md5PasswordEncoder passwordEncoder()
	{
		Md5PasswordEncoder md5 = new Md5PasswordEncoder() {
			@Override
			public boolean isPasswordValid(String encPass, String rawPass, Object salt)
			{
				String pass1 = "" + encPass;
				String pass2 = encodePassword(rawPass, salt).toUpperCase();
				return CustomPasswordEncoderUtil.equals(pass1, pass2);
			}
		};
		return md5;
	}
	/**
	 * 权限管理器配置
	 */
	@Override
	@Bean
	public AuthenticationManager authenticationManagerBean() throws Exception
	{
		return super.authenticationManagerBean();
	}
	/**
	 * 查询用户的sql
	 */
	private String getUserQuery()
	{
		return "SELECT username as username, password as password,1 FROM oauth_user_info WHERE username = ?";
	}
	/**
	 * 查询角色的sql
	 */
	private String getAuthoritiesQuery()
	{
		/*return "SELECT a.username username,c.role_cd role FROM user_info  a"+
				" LEFT JOIN usr_user_role b ON b.user_cd = a.user_cd"+
				" LEFT JOIN usr_role c ON c.role_cd = b.role_cd"+
				" WHERE a.username = ?";*/
		return "SELECT b.username,org_role_cd role FROM oauth_user_role a "
				+ "RIGHT JOIN (SELECT user_cd,username FROM oauth_user_info where username=?) b "
				+ "on a.user_cd=b.user_cd";
	}
}
